import os
import signal
import sys
import  time

from channel import channel_factory
from common import const
from config import load_config
from plugins import *
import threading

def sigterm_handler_wrap(_signo):
    old_handler = signal.getsignal(_signo)

    def func(_signo,_stack_frame):
        logger.info("signal {} received, exiting...".format(_signo))
        conf().save_user_datas()


def start_channel(channel_name:str):
    channel = channel_factory.create_channel(channel_name)
def run():
    try:
        # 加载配置项
        load_config()
        # 程序结束运行
        sigterm_handler_wrap(signal.SIGINT)
        # kill进程
        sigterm_handler_wrap(signal.SIGTERM)

        #创建channel
        channel_name = conf().get("channel_type","wx")

        if "--cmd" in sys.argv:
            channel_name = "terminal"

        if channel_name == "wxy":
            os.environ["WECHATY_LOG"] = "warn"

        start_channel(channel_name)

        while True:
            time.sleep(1)
    except Exception as e:
        logger.error("App startup failed!")
        logger.exception(e)

if __name__ == '__main__':
    run()